package com.lms.logistics_management_system.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lms.logistics_management_system.common.Constants;
import com.lms.logistics_management_system.common.Result;
import com.lms.logistics_management_system.controller.dto.SaveDiagnosticResultDto;
import com.lms.logistics_management_system.controller.dto.UserDTO;
import com.lms.logistics_management_system.controller.dto.UserInfoDto;
import com.lms.logistics_management_system.entity.Doctor;
import com.lms.logistics_management_system.entity.User;
import com.lms.logistics_management_system.mapper.DoctorMapper;
import com.lms.logistics_management_system.service.DoctorService;
import com.lms.logistics_management_system.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RestController
@RequestMapping("/doctor")
public class DoctorController {
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private DoctorMapper doctorMapper;

    /*
     * 登录接口
     * */
    @PostMapping("/login")
    public Result login(@RequestParam String doctorId,@RequestParam String password){
        String username = doctorId;
        //校验
        if(StrUtil.isBlank(username)||StrUtil.isBlank(password)){
            return Result.error(Constants.CODE_400,"参数错误");
        }
        Map<String,Object>res = doctorService.login(username,password);
        return Result.success(res);
    }


    //新增和修改
    @PostMapping("/save")
    public Result save(@RequestBody Doctor doctor){
        return Result.success(doctorService.saveUser(doctor));
    }

    //查询所有表格信息
    @GetMapping
    public List<Doctor> findAll(){
        return doctorService.list();
    }

    //删除
    @DeleteMapping()
    public boolean delete(@RequestParam Integer doctorId){return doctorService.removeByDoctorId(doctorId);}
    //批量删除
    @PostMapping("/del/bash")
    public boolean deleteBash(@RequestBody List<Integer> doctorIds){return doctorService.removeByDoctorIds(doctorIds);}

    //mybitis-plus方式
    @GetMapping("/page")
    public IPage<User> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                @RequestParam (defaultValue = "")String search){
        //若没有传值，则赋默认值，防止将所有数据筛选出来
        IPage<Doctor> page=new Page<>(pageNum,pageSize);
        QueryWrapper queryWrapper=new QueryWrapper<Doctor>();
        queryWrapper.like("doctor_id",search);
        queryWrapper.or();
        queryWrapper.like("doctor_name",search);
        queryWrapper.or();
        queryWrapper.like("doctor_email",search);
        queryWrapper.or();
        queryWrapper.like("doctor_phone_number",search);
        queryWrapper.or();
        queryWrapper.like("department_id",search);
        queryWrapper.or();
        queryWrapper.like("room_id",search);
        queryWrapper.orderByDesc("doctor_id");
        return doctorService.page(page,queryWrapper);
    }

    /*
     * 导出功能，导出当前页面中load的对象
     * */
    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        //从数据库查出数据
        List<Doctor>list = doctorService.list();
        System.out.println(list.get(0).getDoctorName());
        //创建工具类writer，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题名
        writer.addHeaderAlias("doctorId","工号");
        writer.addHeaderAlias("doctorPassword","密码");
        writer.addHeaderAlias("doctorName","姓名");
        writer.addHeaderAlias("doctorEmail","邮箱");
        writer.addHeaderAlias("doctorPhoneNumber","电话");
        writer.addHeaderAlias("departmentId","科号");
        writer.addHeaderAlias("roomId","室号");
        writer.addHeaderAlias("doctorIsAdmin","是否为管理员");
        //将list对象一次性写入到excel中，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应的格式固定写法
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        Date nowtime=new Date();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
        String nowtimstr=sdf.format(nowtime);//Date类型转换为字符串
        String fileName = URLEncoder.encode("医生信息"+nowtimstr,"UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");

        //获取输出流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }

    /*
     *
     * excel导入接口
     * @prama
     * @throws Exception
     * */
    @PostMapping("/import")
    public boolean imp(MultipartFile file)throws Exception{
        InputStream inputStream=file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<Doctor> list=reader.readAll(Doctor.class);
        return doctorService.saveBatch(list);
    }

    @PostMapping("/token")
    public Result token(){return Result.success();}

    /**
     * 获取医生个人信息接口
     * @prama doctorId
     * @return Result
     * */
    @GetMapping("/getDoctorInfo")
    public Result getDoctorInfo(@RequestParam Integer doctorId){
        Map<String,Object>res=new HashMap<>();
        Doctor doctor=doctorMapper.getByDoctorId(doctorId);
        res.put("doctor",doctor);
        String departmentName = doctorMapper.getDepartmentName(doctor.getDepartmentId());
        res.put("departmentName",departmentName);
        return Result.success(res);
    }

    /**
     * 更改医生密码
     * @prama doctorId
     * @param password
     * @param newpassword
     * @return bool是否修改成功
     * */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestParam Integer doctorId,
                                 @RequestParam String password,
                                 @RequestParam String newpassword){
        return doctorService.changePassword(doctorId,password,newpassword);
    }


    /**
     * 根据用户openid以及当前排到的科室号，医生电脑显示相对应的人的能够在这个科室体检的项目的信息（不包括结果，只有项目名称）患者第一次体检时调用
     * @param reservationId
     * @param doctorId
     * @return Result
     * data中返回一个包含有订单号以及项目列表的map
     * */
    @GetMapping("/getDepartmentItem")
    public Result getDepartmentItem(@RequestParam Integer reservationId,
                                    @RequestParam Integer doctorId){
        return Result.success(doctorService.getDepartmentItem(reservationId,doctorId));
    }
    /**
     * 根据医生的doctorid获取医生的诊断历史记录
     * @param doctorId
     * @return Result
     * data中返回一个历史记录列表，有单号和体检人姓名以及病人诊断时间(时间逆序，晚来的在最前面)
     * */
    @GetMapping("/getHistoryDiagnostic")
    public  Result getHistoryDiagnostic(@RequestParam Integer doctorId){
        return Result.success(doctorService.getHistoryDiagnostic(doctorId));
    }

    /**
     * 显示某个医生负责的订单的历史诊断信息
     * @param reservationId
     * @param doctorId
     * @return 返回一个map含有item项目列表以及所有检测结果的列表
     *
     */

    @GetMapping ("/getDiagnosticInfo")
    public Result getDiagnosticInfo(@RequestParam Integer reservationId,
                                    @RequestParam Integer doctorId){
        return Result.success(doctorService.getDiagnosticInfo(reservationId,doctorId));
    }




    /**
     * 保存体检信息，根据医生doctorId和reservationId是否存在来判断是插入还是更新数据
     * @body saveDiagnosticResultDto 其中包含reservationId,doctorId,List<DiagnosticResult>
     * @return Reault，其中包含一个boolean类型的数据代表是否保存成功
     * */
    @PostMapping("/saveDiagnostic")
    public Result saveDiagnostic(@RequestBody SaveDiagnosticResultDto saveDiagnosticResultDto){
        return Result.success(doctorService.saveDiagnostic(saveDiagnosticResultDto,false));
    }

    /**
     * 医生提交诊断，不做修改，在保存的基础上修改订单的完成状态
     *  @body saveDiagnosticResultDto 其中包含reservationId,doctorId,List<DiagnosticResult>
     *  @return Reault，其中包含一个boolean类型的数据代表是否提交成功
     * */
    @PostMapping("/submitDiagnostic")
    public Result submitDiagnostic(@RequestBody SaveDiagnosticResultDto saveDiagnosticResultDto){
        return Result.success(doctorService.saveDiagnostic(saveDiagnosticResultDto,true));
    }





}
